package net.pws.oos.biz.query.impl;

import java.util.ArrayList;
import java.util.List;

import net.pws.oos.biz.model.Attachment;
import net.pws.oos.biz.model.PhotoMarker;
import net.pws.oos.biz.query.AttachmentFinder;
import net.pws.oos.biz.query.parameter.AttachmentQueryParameter;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings({ "unchecked" })
public class DefaultAttachmentFinder extends AbstractFinder implements AttachmentFinder {

	public List<Attachment> getAttachmentList(
			AttachmentQueryParameter queryParameter) {
		StringBuilder hql = new StringBuilder("from Attachment where 1=1 ");
		List<Object> params = new ArrayList<Object>();
		if (StringUtils.isNotEmpty(queryParameter.getResourceId())) {
			hql.append(" and resourceId=? ");
			params.add(queryParameter.getResourceId());
		}
		if (StringUtils.isNotEmpty(queryParameter.getType())) {
			hql.append(" and type=? ");
			params.add(queryParameter.getType());
		}

		return entityManager.findList(hql.toString(), params.toArray());
	}

	public List<Attachment> getPhotos(String resourceId) {
		AttachmentQueryParameter parameter = new AttachmentQueryParameter();
		parameter.setResourceId(resourceId);
		parameter.setType(Attachment.PHOTO_TYPE);
		return getAttachmentList(parameter);
	}

	public Attachment getAttachment(String checkCode, String resourceId) {
		return (Attachment) entityManager
				.findFirst(
						"from Attachment t where t.checkCode = ? and t.resourceId = ? ",
						new Object[] { checkCode, resourceId });
	}

	@Override
	public List<PhotoMarker> getPhotoMarkers(String photoId) {
		String hql = "from PhotoMarker where mediaId=? order by createDate ";
		return entityManager.findList(hql, new Object[] { photoId });
	}

}
